package com.edgclub.edg.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.edgclub.edg.Constant;
import com.edgclub.edg.R;
import com.edgclub.edg.adapter.BBCommentImageAdapter;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.RechargeApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.UploadApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.api.param.RechargeParam;
import com.edgclub.edg.constant.BBConstant;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.lacation.BaiduLocationUtil;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.model.Topic;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.TopicData;
import com.edgclub.edg.task.GzTopicImageUpload;
import com.edgclub.edg.uc.DeleteDialog;
import com.edgclub.edg.uc.GzVoiceRecorderView;
import com.edgclub.edg.uc.SelectImageDialog;
import com.edgclub.edg.uc.TopicRecordDialog;
import com.edgclub.edg.uc.YueHeiDialog;
import com.edgclub.edg.utils.util.CryptUtil;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.MediaPlayerUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.TopicPrefUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.easeui.model.TopicImageInfo;
import com.rockerhieu.emojicon.EmojiconEditText1;
import com.rockerhieu.emojicon.EmojiconGridFragment;
import com.rockerhieu.emojicon.EmojiconsFragment;
import com.rockerhieu.emojicon.emoji.Emojicon;
import com.rockerhieu.emojicon.emoji.SerializeManager;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import me.nereo.multi_image_selector.bean.Image;
import me.nereo.multi_image_selector.utils.FileUtils;

import static com.edgclub.edg.uc.GzVoiceRecorderView.OnTouchListener;


public class GzTopicSendActivity extends GzBaseTooolBarActivity implements
        OnClickListener, EmojiconGridFragment.OnEmojiconClickedListener,
        EmojiconsFragment.OnEmojiconBackspaceClickedListener,
        BBCommentImageAdapter.CloseclickListener, VolleyListener {

    // 请求加载系统照相机
    private static final int REQUEST_CAMERA = 1;
    private static final int REQUEST_IMAGE = 2;

    private EmojiconEditText1 topic_create_content;
    private TopicApi topicApi;
    private UploadApi uploadApi;


    private Topic topic;
    private ArrayList<PostsAlbum> deleteAlbumList;//删除图片列表
    private boolean isUpdate = false;
    private String content;
    private double lat = 0;
    private double lon = 0;
    private String locationString = "";
    private String showLoc = "1";
    private TopicPrefUtils topicPrefUtils;

    private User user;

    private ImageView iv_emoji1, iv_emoji2, iv_image1, iv_image2, iv_voice1, iv_voice2, iv_red_packet1, iv_red_packet2;
    private ImageView iv_select_photo;
    private TextView tv_location1, tv_location2;
    private ImageView closelocation1, closelocation2;
    private FrameLayout emojiconslayout;
    private LinearLayout ll_photo;
    private RecyclerView horizontal_listView;
    private TextView tv_image_num, tv_num, tv_num2;
    private BBCommentImageAdapter commentImageAdapter;

    private RelativeLayout parent, recordlayout;
    private LinearLayout btn_layout1, btn_layout2;

    private ArrayList<TopicImageInfo> infos;
    private ArrayList<Image> selectPathList;
    public static int maxImageCount = 9;

    private boolean ishasAlbum = false;

    private boolean emojiStatus = false;

    /*****************
     * 发红包
     *********************/
    private RelativeLayout redpacketlayout;
    private ImageView red_packet_close;
    private TextView red_packet2_dot,red_packet1_dot;
    private String redDeleteMsg = "该发帖含有红包，取消发送红包金额将自动存入钱包，确定要删除帖子吗？";
    private boolean isFinishActivity = false;
    public static String redId = "";
    public static String redNum = "";
    public static String redTitle = "";
    private boolean isdeleteRed = false;
    private RechargeApi rechargeApi;

    /**
     * ************ 录音 ************************
     */
    protected GzVoiceRecorderView voiceRecorderView;
    private ImageView promptview, promptview2; // 录音上的红点
    private TextView record_repeat_btn;// 重录按钮
    private ImageView record_play_btn, record_sound_btn;// 播放按钮 录音按钮
    private FrameLayout btnRecord;
    private TextView tv_voice_time;
    private boolean isHasRecorde = false;// 是否有录音
    /**
     * ************ 播放 ************************
     */
    private MediaPlayerUtil meidaPlayerUtil;
    private String voicePath;
    private int recordeTime;
    private AnimationDrawable voiceAnimation = null;
    private ImageView yuehei1,yuehei2;

    //图片
    private File mTmpFile;

    //定位
    BaiduLocationUtil baiduLocationUtil;

//	private Topic createTopic;


    @Override
    public int getContentView() {
        return R.layout.activity_gz_launchtopic;
    }

    @Override
    public void setTitleBarView() {
        setCustomActionBar();
        right_layout.setVisibility(View.VISIBLE);
        title.setText("发帖");
        right_text.setText("发送");
        right_text.setOnClickListener(this);
        main_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isUpdate && saveTopic()) {
                    showToast("帖子内容已保存");
                }
                finish();
            }
        });
    }

    @Override
    public void onPause() {
        if (meidaPlayerUtil.isPlaying()) {
            meidaPlayerUtil.stopPlayVoice();
        }
        super.onPause();
    }

    @Override
    public void initView() {
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
        topic_create_content = (EmojiconEditText1) findViewById(R.id.topic_create_content);
        topic_create_content.setOnClickListener(this);
        //定位
        tv_location1 = (TextView) findViewById(R.id.tv_location1);
        tv_location2 = (TextView) findViewById(R.id.tv_location2);
        closelocation1 = (ImageView) findViewById(R.id.closelocation1);
        closelocation2 = (ImageView) findViewById(R.id.closelocation2);
        yuehei1 = (ImageView) findViewById(R.id.yuehei1);
        yuehei2 = (ImageView) findViewById(R.id.yuehei2);
        yuehei1.setOnClickListener(this);
        yuehei2.setOnClickListener(this);

        tv_location1.setOnClickListener(this);
        tv_location2.setOnClickListener(this);
        closelocation1.setOnClickListener(this);
        closelocation2.setOnClickListener(this);
        //表情，图片
        iv_emoji1 = (ImageView) findViewById(R.id.iv_emoji1);
        iv_emoji2 = (ImageView) findViewById(R.id.iv_emoji2);
        iv_image1 = (ImageView) findViewById(R.id.iv_image1);
        iv_image2 = (ImageView) findViewById(R.id.iv_image2);
        iv_voice1 = (ImageView) findViewById(R.id.iv_voice1);
        iv_voice2 = (ImageView) findViewById(R.id.iv_voice2);
        iv_red_packet1 = (ImageView) findViewById(R.id.iv_red_packet1);
        iv_red_packet2 = (ImageView) findViewById(R.id.iv_red_packet2);
        iv_select_photo = (ImageView) findViewById(R.id.iv_select_photo);
        btn_layout1 = (LinearLayout) findViewById(R.id.btn_layout1);
        btn_layout2 = (LinearLayout) findViewById(R.id.btn_layout2);
        recordlayout = (RelativeLayout) findViewById(R.id.recordlayout);
        redpacketlayout = (RelativeLayout) findViewById(R.id.redpacketlayout);
        emojiconslayout = (FrameLayout) findViewById(R.id.emojicons);
        iv_emoji1.setOnClickListener(this);
        iv_emoji2.setOnClickListener(this);
        iv_image1.setOnClickListener(this);
        iv_image2.setOnClickListener(this);
        iv_voice1.setOnClickListener(this);
        iv_voice2.setOnClickListener(this);
        iv_red_packet1.setOnClickListener(this);
        iv_red_packet2.setOnClickListener(this);
        iv_select_photo.setOnClickListener(this);

        //发红包
        red_packet_close = (ImageView) findViewById(R.id.red_packet_close);
        red_packet1_dot = (TextView) findViewById(R.id.red_packet1_dot);
        red_packet2_dot = (TextView) findViewById(R.id.red_packet2_dot);
        red_packet_close.setOnClickListener(this);

        //语音
        promptview = (ImageView) findViewById(R.id.promptview);
        promptview2 = (ImageView) findViewById(R.id.promptview2);
        record_repeat_btn = (TextView) findViewById(R.id.record_repeat_btn);
        record_sound_btn = (ImageView) findViewById(R.id.record_sound_btn);
        record_play_btn = (ImageView) findViewById(R.id.record_play_btn);
        record_repeat_btn.setOnClickListener(this);
        record_play_btn.setOnClickListener(this);

        //图片
        ll_photo = (LinearLayout) findViewById(R.id.ll_photo);
        tv_image_num = (TextView) findViewById(R.id.tv_image_num);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_num2 = (TextView) findViewById(R.id.tv_num2);
        horizontal_listView = (RecyclerView) findViewById(R.id.horizontal_listView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        horizontal_listView.setLayoutManager(layoutManager);
        commentImageAdapter = new BBCommentImageAdapter(this);
        horizontal_listView.setAdapter(commentImageAdapter);
        commentImageAdapter.setCloseclickListener(this);

        parent = (RelativeLayout) findViewById(R.id.parent);
        parent.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    @Override
                    public void onGlobalLayout() {

                        // 比较Activity根布局与当前布局的大小
                        int heightDiff = parent.getRootView().getHeight()
                                - parent.getHeight();
                        if (heightDiff > 400) {
//							tv_bg.setVisibility(View.VISIBLE);
                            btn_layout1.setVisibility(View.GONE);
                            btn_layout2.setVisibility(View.VISIBLE);
                            // 大小超过100时，一般为显示虚拟键盘事件
                        } else if (heightDiff <= 400) {
                            // 大小小于100时，为不显示虚拟键盘或虚拟键盘隐藏
                            btn_layout1.setVisibility(View.VISIBLE);
                            btn_layout2.setVisibility(View.GONE);
//							if(emojiconslayout.getVisibility() == View.GONE &&
//									ll_photo.getVisibility()==View.GONE && recordlayout.getVisibility()==View.GONE
//									&& redpacketlayout.getVisibility() == View.GONE){
////								tv_bg.setVisibility(View.VISIBLE);
//							}
//
                            if (emojiconslayout.getVisibility() == View.INVISIBLE) {
                                emojiconslayout.setVisibility(View.VISIBLE);
                            }
                            if (ll_photo.getVisibility() == View.INVISIBLE) {
                                ll_photo.setVisibility(View.VISIBLE);
                            }
                            if (recordlayout.getVisibility() == View.INVISIBLE) {
                                recordlayout.setVisibility(View.VISIBLE);
                            }
                            if (redpacketlayout.getVisibility() == View.INVISIBLE) {
                                redpacketlayout.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });


        setEmojiconFragment(false);

        /************** 录音 ***************/
        // 按住说话录音控件
        voiceRecorderView = (GzVoiceRecorderView) findViewById(com.hyphenate.easeui.R.id.voice_recorder);
        btnRecord = (FrameLayout) findViewById(R.id.record_btn);
        tv_voice_time = (TextView) findViewById(R.id.tv_voice_time);
        btnRecord.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return voiceRecorderView.onPressToSpeakBtnTouch(view, motionEvent, new GzVoiceRecorderView.GzVoiceRecorderCallback() {
                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        voicePath = voiceFilePath;
                        recordeTime = voiceTimeLength;
                        Log.d("ACTION_UPddddd", voiceFilePath
                                + "....." + voiceTimeLength);
                        tv_voice_time.setText(voiceTimeLength + "\"");
                        isHasRecorde = true;
                        setIsVoiceState(isHasRecorde);
                    }
                });
            }
        });


        // 扬声器模式
        AudioManager audioManager = (AudioManager) this
                .getSystemService(Context.AUDIO_SERVICE);
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setSpeakerphoneOn(true);
    }

    class MyRecorderCallback implements GzVoiceRecorderView.GzVoiceRecorderCallback {

        @Override
        public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
            btnRecord.setEnabled(false);
        }
    }


    @Override
    public void initData() {
        topicApi = new TopicApi(this);
        uploadApi = new UploadApi(this);
        meidaPlayerUtil = new MediaPlayerUtil(this);
        UserPrefUtils prefUtils = new UserPrefUtils(this);
        user = prefUtils.getUser();
        selectPathList = new ArrayList<>();
        infos = new ArrayList<>();
        deleteAlbumList = new ArrayList<>();
        rechargeApi = new RechargeApi(this);
        topic = (Topic) SerializeManager.loadFile(Constant.SAVETOPIC+user.getId()+"");
        topicPrefUtils = new TopicPrefUtils(this);
        //修改帖子
        if (getIntent().hasExtra("topic")) {
            topic = (Topic) getIntent().getSerializableExtra("topic");
            isUpdate = true;
            setContent(topic);
            if(topic.getCategory().equals("2")){
                yuehei1.setSelected(true);
                yuehei2.setSelected(true);
            }else{
                yuehei1.setSelected(false);
                yuehei2.setSelected(false);
            }
        } else if (topic != null) {
            showupdateDialog(topic);
        }

        // 开启定位
        baiduLocationUtil = new BaiduLocationUtil(getApplicationContext(), new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                lat = bdLocation.getLatitude();
                lon = bdLocation.getLongitude();
                locationString = bdLocation.getAddrStr();
                tv_location1.setText(locationString + "");
                tv_location2.setText(locationString + "");
            }
        });
        baiduLocationUtil.startBDLocation();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(redId)) {
            redpacketlayout.setVisibility(View.INVISIBLE);
            red_packet1_dot.setVisibility(View.VISIBLE);
            red_packet2_dot.setVisibility(View.VISIBLE);
            recordlayout.setVisibility(View.GONE);
            emojiconslayout.setVisibility(View.GONE);
            closeKeyboard();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub 不可去掉
    }

    private void setEmojiconFragment(boolean useSystemDefault) {
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.emojicons,
                        EmojiconsFragment.newInstance(useSystemDefault))
                .commit();
    }

    /**
     * 表情处理
     */
    @Override
    public void onEmojiconClicked(Emojicon emojicon) {
        EmojiconsFragment.input(topic_create_content, emojicon);
    }

    @Override
    public void onEmojiconBackspaceClicked(View v) {
        EmojiconsFragment.backspace(topic_create_content);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.closelocation1:
            case R.id.closelocation2:
                closelocation1.setVisibility(View.GONE);
                closelocation2.setVisibility(View.GONE);
                tv_location1.setText(StringUtils.getString(R.string.accordingaddress));
                tv_location2.setText(StringUtils.getString(R.string.accordingaddress));
                showLoc = "0";
                MobclickAgent.onEvent(this,"EC_POST_CREATE_HIDE_LOCATION");

                break;
            case R.id.tv_location1:
            case R.id.tv_location2:
                if (tv_location1.getText().equals(StringUtils.getString(R.string.accordingaddress))) {
                    closelocation1.setVisibility(View.VISIBLE);
                    closelocation2.setVisibility(View.VISIBLE);
                    tv_location1.setText(locationString);
                    tv_location2.setText(locationString);
                    showLoc = "1";
                }

                break;
            case R.id.iv_emoji1:
            case R.id.iv_emoji2:
                recordlayout.setVisibility(View.GONE);
                ll_photo.setVisibility(View.GONE);
                redpacketlayout.setVisibility(View.GONE);
                if (emojiStatus) {
                    emojiStatus = false;
                    emojiconslayout.setVisibility(View.GONE);
                    iv_emoji1.setImageResource(R.drawable.send_emoji);
                    showKeyboard();
                } else {
                    emojiStatus = true;
                    iv_emoji1.setImageResource(R.drawable.send_keyboard);
                    closeKeyboard();
                    emojiconslayout.setVisibility(View.INVISIBLE);
                }
                iv_voice1.setSelected(false);
                iv_image1.setSelected(false);
                break;
            case R.id.iv_image1:
            case R.id.iv_image2:
                if (iv_image1.isSelected()) return;
                if (iv_image2.isSelected()) return;
                closeKeyboard();
                emojiconslayout.setVisibility(View.GONE);
                recordlayout.setVisibility(View.GONE);
                redpacketlayout.setVisibility(View.GONE);
                ll_photo.setVisibility(View.INVISIBLE);
                iv_voice1.setSelected(false);
                iv_image1.setSelected(true);
                break;

            case R.id.iv_voice1:
            case R.id.iv_voice2:
                if (iv_voice1.isSelected()) return;
                if (iv_voice2.isSelected()) return;
                closeKeyboard();
                emojiconslayout.setVisibility(View.GONE);
                ll_photo.setVisibility(View.GONE);
                redpacketlayout.setVisibility(View.GONE);
                recordlayout.setVisibility(View.INVISIBLE);
                iv_voice1.setSelected(true);
                iv_image1.setSelected(false);
                MobclickAgent.onEvent(this,"EC_POST_CREATE_ADD_AUDIO");

                break;
            case R.id.iv_red_packet1:
            case R.id.iv_red_packet2:
                emojiconslayout.setVisibility(View.GONE);
                ll_photo.setVisibility(View.GONE);
                recordlayout.setVisibility(View.GONE);
                iv_voice1.setSelected(false);
                iv_image1.setSelected(false);
                closeKeyboard();
                sendredpacket();
                MobclickAgent.onEvent(this,"EC_POST_CREATE_ADD_RED_POCKET");
                break;

            case R.id.iv_select_photo:
                selectImage();
                break;

            case R.id.topic_create_content:
                emojiStatus = false;
                emojiconslayout.setVisibility(View.GONE);
                ll_photo.setVisibility(View.GONE);
                recordlayout.setVisibility(View.GONE);
                redpacketlayout.setVisibility(View.GONE);
                iv_emoji1.setImageResource(R.drawable.send_emoji);
                iv_image1.setSelected(false);
                iv_voice1.setSelected(false);
                showKeyboard();
                break;

            case R.id.record_play_btn:// 播放
                if (isHasRecorde) {
                    meidaPlayerUtil.playVoice(voicePath);
                    record_play_btn.setVisibility(View.GONE);
                    record_sound_btn.setVisibility(View.VISIBLE);
                    record_sound_btn
                            .setImageResource(R.drawable.voice_to_play_send_topic);
                    voiceAnimation = (AnimationDrawable) record_sound_btn
                            .getDrawable();
                    voiceAnimation.start();
                    meidaPlayerUtil.getMediaPlayer().setOnCompletionListener(
                            new MediaPlayer.OnCompletionListener() {

                                @Override
                                public void onCompletion(MediaPlayer mp) {
                                    // TODO Auto-generated method stub
                                    meidaPlayerUtil.stopPlayVoice();
                                    voiceAnimation.stop();
                                    record_play_btn.setVisibility(View.VISIBLE);
                                    record_sound_btn.setVisibility(View.GONE);
                                }
                            });
                }
                break;
            case R.id.record_repeat_btn:// 重录
                final TopicRecordDialog dialog = new TopicRecordDialog(
                        GzTopicSendActivity.this);
                dialog.show();
                dialog.setOnTopicRecordDialogClickListener(new TopicRecordDialog.TopicRecordDialogClickListener() {

                    @Override
                    public void onRecordListener() {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        meidaPlayerUtil.stopPlayVoice();
                        voiceRecorderView.discardRecording();
                        isHasRecorde = false;
                        setIsVoiceState(isHasRecorde);
                        if (null != topic && topic.getAudios() != null && topic.getAudios().size() > 0) {//修改帖子---删除语音
                            deleteAlbumList.add(topic.getAudios().get(0));
                            topic.getAudios().clear();
                        }
                    }
                });

                break;
            case R.id.red_packet_close:
                showRedDeleteDialog("删除红包后，红包余额将自动转存到您的钱包中，是否确认删除？");
                break;

            case R.id.right_text://发帖
                closeKeyboard();
                if (isUpdate) {
                    content = topic_create_content.getText().toString().trim();
                    saveImg(topic);
                    if (TextUtils.isEmpty(content) && selectPathList.size() == 0
                            && !isHasRecorde) {
                        Toast.makeText(this, StringUtils.getString(R.string.entertopiccontent), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    boolean isyueheichange = false; //约黑按钮是否改变
                    if(topic.getCategory().equals("2")){ //约黑贴
                        if(!yuehei1.isSelected()){
                            isyueheichange  = true;
                        }
                    }else{
                        if(yuehei1.isSelected()){
                            isyueheichange = true;
                        }
                    }

                    if (!topic.getContent().equals(content) || isyueheichange) {//内容修改
                        update();
                    } else if (deleteAlbumList.size() > 0) {
                        deleteImg();
                    } else if (infos.size() > 0) {
                        showDialog("正在发帖...", false);
                        new GzTopicImageUpload(GzTopicSendActivity.this, infos);
                    } else {
                        updataFinish();
                    }

                } else {
                    create();
                }
                break;
            case R.id.yuehei1:
            case R.id.yuehei2:
                yuehei2.setSelected(!yuehei2.isSelected());
                yuehei1.setSelected(!yuehei1.isSelected());
                if (yuehei1.isSelected()) {
                    if (!topicPrefUtils.getTopicYuehei()){
                        closeKeyboard();
                        YueheiDialog();
                    }else {

                    }
                }
                break;

            default:
                break;
        }
    }
    private void YueheiDialog() {
        final YueHeiDialog dialog = YueHeiDialog.create(this, true);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setCancelListener(new YueHeiDialog.CancelClickListener() {

            @Override
            public void cancelClick(boolean b) {
                topicPrefUtils.setTopicYuehei(b);
            }
        });

        dialog.setSubmitListener(new YueHeiDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                dialog.dismiss();

            }
        });
    }

    private void create() {
        PostsParam postsParam = new PostsParam();
        content = topic_create_content.getText().toString().trim();
        postsParam.setUserId(user.getId());
        if(yuehei1.isSelected()){
            postsParam.setBlack("1");
        }else{
            postsParam.setBlack("0");
        }

        postsParam.setContent(content + "");
        if (!TextUtils.isEmpty(redId)) {
            postsParam.setRedId(redId);
            postsParam.setRedNum(redNum);
        }
        postsParam.setLat(lat + "");
        postsParam.setLon(lon + "");
        postsParam.setLocation(locationString);
        if (selectPathList.size() > 0 || isHasRecorde) {
            postsParam.setHasAlbum("1");
        } else {
            postsParam.setHasAlbum("0");
        }

        if ("".equals(locationString)) {
            postsParam.setShowLoc("0");
        } else {
            postsParam.setShowLoc(showLoc);
        }

        if (TextUtils.isEmpty(content) && selectPathList.size() == 0
                && !isHasRecorde) {
            Toast.makeText(this, StringUtils.getString(R.string.entertopiccontent), Toast.LENGTH_SHORT).show();
            return;
        }
        topicApi.create(postsParam, this);

    }

    private void update() {
        PostsParam postsParam = new PostsParam();
        content = topic_create_content.getText().toString().trim();
        postsParam.setUserId(user.getId());
        postsParam.setContent(content + "");
        if(yuehei1.isSelected()){
            postsParam.setBlack("1");
        }else{
            postsParam.setBlack("0");
        }
        postsParam.setPostsId(topic.getPostsId());
        topicApi.update(postsParam, this);
    }

    private void updateSeq(ArrayList<PostsAlbum> albums) {
        PostsParam postsParam = new PostsParam();
        content = topic_create_content.getText().toString().trim();
        postsParam.setUserId(user.getId());
        String seqs = null;
        for (int i = 0; i < albums.size(); i++) {
            if (i == 0) {
                seqs = albums.get(i).getId() + "-" + i;
            } else {
                seqs = seqs + ";" + albums.get(i).getId() + "-" + i;
            }
        }
        if (isHasRecorde && voicePath != null && voicePath.startsWith("http")) {
            seqs = seqs + ";" + topic.getAudios().get(0).getId();
            if (seqs == null) {
                seqs = topic.getAudios().get(0).getId() + "-" + selectPathList.size();
            } else {
                seqs = seqs + ";" + topic.getAudios().get(0).getId() + "-" + selectPathList.size();
            }
        }
        postsParam.setSeqs(seqs);
        postsParam.setPostsId(topic.getPostsId());
        topicApi.updateSeq(postsParam, this);
    }

    private void deleteImg() {
        PostsParam postsParam = new PostsParam();
        postsParam.setUserId(user.getId());
        postsParam.setPostsId(topic.getPostsId());
        String alId = null;
        for (int i = 0; i < deleteAlbumList.size(); i++) {
            if (i == 0) {
                alId = deleteAlbumList.get(i).getId() + "";
            } else {
                alId = alId + "," + deleteAlbumList.get(i).getId();
            }
        }
        postsParam.setAlbumId(alId);
        topicApi.deleteImg(postsParam, this);
    }

    private void saveImg(Topic topic) {
        for (int i = 0; i < selectPathList.size(); i++) {
            if (!selectPathList.get(i).path.startsWith("http")) {
                TopicImageInfo info = new TopicImageInfo();
                info.setTopicId(topic.getPostsId());
                info.setPath(selectPathList.get(i).path);
                info.setName(selectPathList.get(i).name);
                info.setUploadstate("false");
                info.setPosition(i);
                if (selectPathList.get(i).isOri) {
                    info.setIsOri("true");
                } else {
                    info.setIsOri("false");
                }
                infos.add(info);
            }
        }
        if (isHasRecorde && voicePath != null && !voicePath.startsWith("http")) {
            TopicImageInfo info = new TopicImageInfo();
            info.setTopicId(topic.getPostsId());
            info.setPath(voicePath);
            info.setName(BBConstant.URL_VOICE_PROTOCOL);
            info.setTime((long) recordeTime);
            info.setUploadstate("false");
            info.setIsOri("false");
            info.setPosition(selectPathList.size());
            infos.add(info);
        }
    }

    private void setIsVoiceState(boolean boo) {
        if (boo) {
            promptview.setVisibility(View.VISIBLE);
            promptview2.setVisibility(View.VISIBLE);
            record_play_btn.setVisibility(View.VISIBLE);
            record_sound_btn.setVisibility(View.GONE);
            record_repeat_btn.setVisibility(View.VISIBLE);
        } else {
            promptview.setVisibility(View.GONE);
            promptview2.setVisibility(View.GONE);
            record_play_btn.setVisibility(View.GONE);
            record_sound_btn
                    .setImageResource(R.drawable.gz_topic_voice_replay3);
            record_sound_btn.setVisibility(View.VISIBLE);
            record_repeat_btn.setVisibility(View.GONE);
            tv_voice_time.setText("");
            recordeTime = 0;
        }

    }

    private void sendredpacket() {
        String gzno = user.getGzno();
        String phone = user.getPhone();
        if (!gzno.equals(phone)) {
            String pass = (String) SerializeManager.loadFile(Constant.peson_hpsw + user.getId());
            if (null != pass && !"".equals(pass)) {
                if (TextUtils.isEmpty(redId)) {
//                    Intent redPacketIntent = new Intent(GzTopicSendActivity.this, GzRedPacketSendActivity.class);
//                    startActivity(redPacketIntent);
                } else {
                    redpacketlayout.setVisibility(View.VISIBLE);
                    red_packet1_dot.setVisibility(View.VISIBLE);
                    red_packet2_dot.setVisibility(View.VISIBLE);
                }
            } else {
                getpass();
            }

        } else {
            banDingDialog();
        }
    }

    private void banDingDialog() {
        final DeleteDialog dialog = DeleteDialog.create(this, true);
        dialog.show();
        dialog.setCancelable(true);
        dialog.setTitle(StringUtils.getString(R.string.prompt));
        dialog.setContent("使用红包功能,\n需要绑定一个安全手机号");
        dialog.setSubmittext("立即绑定");
        dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

            @Override
            public void cancelClick() {
                dialog.dismiss();
            }
        });
        dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                Intent intent = new Intent(GzTopicSendActivity.this,
                        GzBindPhomeActivity.class);
                intent.putExtra("frompage", "hongbao");
                startActivity(intent);
                dialog.dismiss();

            }
        });
    }

    private boolean isLoading = false; // 是否正在加载

    private void getpass() {
        if (isLoading) {
            return;
        }
        RechargeApi rechargeApi = new RechargeApi(this);
        RechargeParam atMeParam = new RechargeParam();
        atMeParam.setUserId(user.getId() + "");
        rechargeApi.getPass(atMeParam, new getMyListener());
    }


    class getMyListener implements VolleyListener {

        @Override
        public void onStart(String tag) {
            isLoading = true;
            showDialog(StringUtils.getString(R.string.getting), true);
        }

        @Override
        public void onSuccess(String response, String tag) {
            isLoading = false;
            dismissDialog();
            if (JSONHelper.isSuccess(response)) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    String psw = jsonObject.optString("data");
                    if (null != psw && !"".equals(psw)) {
                        SerializeManager.saveFile(CryptUtil.md5(psw), Constant.peson_hpsw + user.getId());
                    } else {
                        setPassDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            isLoading = false;
            dismissDialog();
            ResultCode.toastVolleyError(GzTopicSendActivity.this, volleyError);
        }
    }

    private void setPassDialog() {
        final DeleteDialog dialog = DeleteDialog.create(this, true);
        dialog.show();
        dialog.setCancelable(true);
        dialog.setTitle(StringUtils.getString(R.string.prompt));
        dialog.setContent("使用红包功能,\n需要设置独立的支付密码");
        dialog.setSubmittext("立即设置");
        dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

            @Override
            public void cancelClick() {
                dialog.dismiss();
            }
        });
        dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                Intent intent = new Intent(GzTopicSendActivity.this,
                        GzPayPassForgetActivity.class);
                intent.putExtra("frompage", "setpass");
                startActivity(intent);
                dialog.dismiss();

            }
        });
    }

    /**
     * 显示键盘
     */
    private void showKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(topic_create_content, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    private void closeKeyboard() {

        InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(topic_create_content.getWindowToken(), 0);
//		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
//			if (getCurrentFocus() != null)
//				manager.hideSoftInputFromWindow(getCurrentFocus()
//						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//		}
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                selectPathList = (ArrayList<Image>) data.getSerializableExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                Log.d("mSelectPath", selectPathList.size() + "--------------");
                updateImage();
            }
        } else if (requestCode == REQUEST_CAMERA) {// 相机拍照完成后，返回图片路径
            closeKeyboard();
            if (resultCode == Activity.RESULT_OK) {
                if (mTmpFile != null) {
                    Image image = new Image(mTmpFile.getAbsolutePath(), mTmpFile.getName(), System.currentTimeMillis(), false);
                    selectPathList.add(image);
                    Log.d("mSelectPath", mTmpFile.getAbsolutePath() + "--------------");
                    updateImage();
                }
            } else {
                while (mTmpFile != null && mTmpFile.exists()) {
                    boolean success = mTmpFile.delete();
                    if (success) {
                        mTmpFile = null;
                    }
                }
            }
        }
    }

    private void updateImage() {
        if (selectPathList.size() > 0) {
            horizontal_listView.setVisibility(View.VISIBLE);
            iv_select_photo.setVisibility(View.GONE);
            tv_num.setVisibility(View.VISIBLE);
            tv_num2.setVisibility(View.VISIBLE);
            tv_num.setText(selectPathList.size() + "");
            tv_num2.setText(selectPathList.size() + "");
        } else {
            tv_num.setVisibility(View.GONE);
            tv_num2.setVisibility(View.GONE);
            iv_select_photo.setVisibility(View.VISIBLE);
            horizontal_listView.setVisibility(View.GONE);
        }
        tv_image_num.setText("已选" + selectPathList.size() + "张，还可以添加" +
                (maxImageCount - selectPathList.size()) + "张");
        commentImageAdapter.setSelectPathList(selectPathList);
        commentImageAdapter.notifyDataSetChanged();
    }


    @Override
    public void onStart(String tag) {
//		if(tag.equals(ApiConfig.APIURL.URL_POSTS_REPLYTOPIC)){
        showDialog("正在发帖...", false);
//		}
    }

    @Override
    public void onSuccess(String response, String tag) {

        if (JSONHelper.isSuccess(response)) {
            if (tag.equals(ApiConfig.APIURL.URL_POSTS_CREATE)) {
                TopicData data = JsonUtil.getMode(response, TopicData.class);
                topic = null;
                topic = data.getData();
                saveImg(topic);
                if (infos.size() > 0) {//有图片或语音
                    new GzTopicImageUpload(GzTopicSendActivity.this, infos);
                } else {
                    updataFinish();
                }

            } else if (tag.equals(ApiConfig.APIURL.URL_POSTS_UPDATE)) {
                if (deleteAlbumList.size() > 0) {
                    deleteImg();
                } else if (infos.size() > 0) {
                    new GzTopicImageUpload(GzTopicSendActivity.this, infos);
                } else {
                    updataFinish();
                }
            } else if (tag.equals(ApiConfig.APIURL.URL_POSTS_UPDATE_DELETE_IMG)) {
                ArrayList<PostsAlbum> albums = topic.getAlbums();
                if (albums.size() > 0 || topic.getAudios().size() > 0) {
                    updateSeq(albums);
                } else if (infos.size() > 0) {
                    new GzTopicImageUpload(GzTopicSendActivity.this, infos);
                } else {
                    updataFinish();

                }
            } else if (tag.equals(ApiConfig.APIURL.URL_POSTS_UPDATE_SEQ)) {
                if (infos.size() > 0) {
                    new GzTopicImageUpload(GzTopicSendActivity.this, infos);
                } else {
                    updataFinish();
                }
            }
        } else {
            dismissDialog();
            showToast(JSONHelper.getResultMsg(response));
        }
    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {
        dismissDialog();
        ResultCode.toastVolleyError(this, volleyError);
    }

    private void updataFinish() {
        if (!TextUtils.isEmpty(topic_create_content.getText().toString().trim())) {
            topic.setContent(topic_create_content.getText().toString().trim());
        }
        ArrayList<PostsAlbum> postsAlbums = new ArrayList<PostsAlbum>();
        for (int i = 0; i < selectPathList.size(); i++) {
            PostsAlbum postsAlbum = new PostsAlbum();
            postsAlbum.setThumbnail(selectPathList.get(i).path);
            postsAlbum.setUrl(selectPathList.get(i).path);
            if (selectPathList.get(i).isOri) {
                postsAlbum.setOriUrl(selectPathList.get(i).path);
            }
            postsAlbum.setWidth(selectPathList.get(i).getWidth());
            postsAlbum.setHeight(selectPathList.get(i).getHeight());
            postsAlbums.add(postsAlbum);
        }
        topic.setAlbums(postsAlbums);
        if (isHasRecorde && voicePath != null && !voicePath.startsWith("http")) {
            PostsAlbum ab = new PostsAlbum();
            ab.setUrl(BBConstant.URL_VOICE_PROTOCOL + recordeTime);
            ab.setThumbnail(voicePath);
            ArrayList<PostsAlbum> audios = new ArrayList<>();
            audios.add(ab);
            topic.setAudios(audios);
        }
        if(yuehei1.isSelected()){
            topic.setBlack("1");
        }else{
            topic.setBlack("0");
        }

        dismissDialog();
        // 将最新的贴子加入我的贴子里
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("event", BroadCastEvent.TOPICCREATENEOTOPIC);
        hashMap.put("topic", topic);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON, ThreadEnforcer.MAIN).post(hashMap);
        redId = "";
        closeKeyboard();
        finish();

    }

    // 图片上传完成
    @Subscribe
    public void uploadImgEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICCREATEUPLOADIMG.equals(event)) {
            dismissDialog();
            String issuccess = (String) map.get("issuccess");
            if (issuccess.equals("true")) {
                ArrayList<PostsAlbum> albums = (ArrayList<PostsAlbum>) map.get("albums");
                uploadImgFinish(albums);
            } else {
                showToast("图片上传失败");
            }
        }
    }

    private void uploadImgFinish(ArrayList<PostsAlbum> albums) {
        if (!TextUtils.isEmpty(topic_create_content.getText().toString().trim())) {
            topic.setContent(topic_create_content.getText().toString().trim());
        }
        ArrayList<PostsAlbum> postsAlbums = new ArrayList<PostsAlbum>();
        for (int i = 0; i < selectPathList.size(); i++) {
            if (selectPathList.get(i).path.startsWith("http")) {
                PostsAlbum postsAlbum = new PostsAlbum();
                postsAlbum.setThumbnail(selectPathList.get(i).path);
                postsAlbum.setUrl(selectPathList.get(i).path);
                if (selectPathList.get(i).isOri) {
                    postsAlbum.setOriUrl(selectPathList.get(i).path);
                }
                postsAlbum.setWidth(selectPathList.get(i).getWidth());
                postsAlbum.setHeight(selectPathList.get(i).getHeight());
                postsAlbums.add(postsAlbum);
            }
        }
        if(albums!=null && albums.size()>0){
            postsAlbums.addAll(albums);
        }
        topic.setAlbums(postsAlbums);
        if (isHasRecorde && voicePath != null && !voicePath.startsWith("http")) {
            PostsAlbum ab = new PostsAlbum();
            ab.setUrl(BBConstant.URL_VOICE_PROTOCOL + recordeTime);
            ab.setThumbnail(voicePath);
            ArrayList<PostsAlbum> audios = new ArrayList<>();
            audios.add(ab);
            topic.setAudios(audios);
        }
        dismissDialog();
        // 将最新的贴子加入我的贴子里
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("event", BroadCastEvent.TOPICCREATENEOTOPIC);
        hashMap.put("topic", topic);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON, ThreadEnforcer.MAIN).post(hashMap);
        redId = "";
        closeKeyboard();
        finish();

    }

    @Override
    public void addImage(int position) {
        if (position == selectPathList.size()) {
            selectImage();
        } else {

        }

    }

    @Override
    public void close(int position) {
        Image image = selectPathList.get(position);
        if (!TextUtils.isEmpty(image.getAlbumId())) {
            PostsAlbum album = new PostsAlbum();
            album.setId(Long.valueOf(image.getAlbumId()));
            deleteAlbumList.add(album);
            topic.getAlbums().remove(position);

        }

        selectPathList.remove(position);
        updateImage();
    }

    private void selectImage() {
        final SelectImageDialog dialog = new SelectImageDialog(
                GzTopicSendActivity.this);
        dialog.show();
        dialog.setSelectDialogClickListener(new SelectImageDialog.SelectDialogClickListener() {
            @Override
            public void ontakePic() {
                showCameraAction();
                dialog.dismiss();
            }

            @Override
            public void onfromImage() {
                jumpSelectImage();
                dialog.dismiss();
            }
        });
    }

    /**
     * 选择相机
     */
    private void showCameraAction() {
        // 跳转到系统照相机
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(this.getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            try {
                mTmpFile = FileUtils.createTmpFile(this);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (mTmpFile != null && mTmpFile.exists()) {
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
                startActivityForResult(cameraIntent, REQUEST_CAMERA);
            } else {
                Toast.makeText(this, "图片错误", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, me.nereo.multi_image_selector.R.string.msg_no_camera, Toast.LENGTH_SHORT).show();
        }
    }

    private void jumpSelectImage() {
        int needToAddNumber2 = maxImageCount - selectPathList.size();
        if (needToAddNumber2 < 0) {
            needToAddNumber2 = 0;
        }
        Intent intent = new Intent(GzTopicSendActivity.this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxImageCount);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择
        if (selectPathList != null && selectPathList.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectPathList);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }


    private void showRedDeleteDialog(String content) {
        final DeleteDialog dialog = DeleteDialog.create(this, true);
        dialog.setTitle(StringUtils.getString(R.string.prompt));
        dialog.setContent(content);
        dialog.setSubmittext(StringUtils.getString(R.string.ok));
        dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

            @Override
            public void cancelClick() {
                dialog.dismiss();
                isFinishActivity = false;
            }
        });
        dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                dialog.dismiss();
                deleteRedPacket();
            }
        });
        dialog.show();
    }

    /**
     * 删除红包
     */
    private void deleteRedPacket() {
        if (isdeleteRed) {
            return;
        }
        RechargeParam rechargeParam = new RechargeParam();
        rechargeParam.setRedId(redId);
        rechargeApi.deleteRed(rechargeParam, new deleteRedListener());
    }

    class deleteRedListener implements VolleyListener {

        @Override
        public void onStart(String tag) {
            isdeleteRed = true;
            showDialog("正在删除红包...", false);
        }

        @Override
        public void onSuccess(String response, String tag) {
            isdeleteRed = false;
            dismissDialog();
            if (JSONHelper.isSuccess(response)) {
                redpacketlayout.setVisibility(View.GONE);
                red_packet1_dot.setVisibility(View.GONE);
                red_packet2_dot.setVisibility(View.GONE);
                redId = "";
                if (isFinishActivity) {
                    finish();
                }

            } else if (JSONHelper.getResultCode(response) == 9121) {
                showToast("支付密码错误");
            } else {
                showToast(response.toString());
            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            dismissDialog();
            showToast(volleyError.toString());
            isdeleteRed = false;
        }

    }

    @Override
    public void onBackPressed() {
        if (!TextUtils.isEmpty(redId)) {
            isFinishActivity = true;
            showRedDeleteDialog(redDeleteMsg);
            return;
        }
        if (!isUpdate && saveTopic()) {
            showToast("帖子内容已保存");
        }
        super.onBackPressed();
    }

    private boolean saveTopic() {
        boolean issave = false;
        if (topic == null) {
            topic = new Topic();
        }
        if (!TextUtils.isEmpty(topic_create_content.getText().toString())) {
            issave = true;
            topic.setContent(topic_create_content.getText().toString() + "");
        }
        ArrayList<PostsAlbum> postsAlbums = new ArrayList<PostsAlbum>();
        for (int i = 0; i < selectPathList.size(); i++) {
            PostsAlbum postsAlbum = new PostsAlbum();
            postsAlbum.setThumbnail(selectPathList.get(i).path);
            postsAlbum.setUrl(selectPathList.get(i).path);
            if (selectPathList.get(i).isOri) {
                postsAlbum.setOriUrl(selectPathList.get(i).path);
            }
            postsAlbums.add(postsAlbum);
            issave = true;
        }
        topic.setAlbums(postsAlbums);
        if (isHasRecorde && voicePath != null && !voicePath.startsWith("http")) {
            PostsAlbum ab = new PostsAlbum();
            ab.setUrl(BBConstant.URL_VOICE_PROTOCOL + recordeTime);
            ab.setThumbnail(voicePath);
            ArrayList<PostsAlbum> audios = new ArrayList<>();
            audios.add(ab);
            topic.setAudios(audios);
            issave = true;
        }
        if (issave) {
            SerializeManager.saveFile(topic, Constant.SAVETOPIC+user.getId()+"");
        }
        return issave;

    }


    private void showupdateDialog(final Topic topic) {
        final DeleteDialog dialog = DeleteDialog.create(this, true);
        dialog.setTitle(StringUtils.getString(R.string.prompt));
        dialog.setContent("你是否继续编辑上次的草稿?");
        dialog.setSubmittext(StringUtils.getString(R.string.ok));
        dialog.setCancelListener(new DeleteDialog.CancelClickListener() {

            @Override
            public void cancelClick() {
                dialog.dismiss();
            }
        });
        dialog.setSubmitListener(new DeleteDialog.SubmitClickListener() {

            @Override
            public void submitClick() {
                setContent(topic);
                File file = new File(Constant.SAVETOPIC+user.getId()+"");
                if (file.exists()) {
                    file.delete();
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    private void setContent(Topic topic) {
        topic_create_content.setText(topic.getContent() + "");
        ArrayList<PostsAlbum> albums = topic.getAlbums();
        ArrayList<PostsAlbum> audios = topic.getAudios();
        for (int i = 0; i < albums.size(); i++) {
            Image image = new Image(albums.get(i).getThumbnail(), albums.get(i).getName(), System.currentTimeMillis(), false);
            if (albums.get(i).getId() != null) {
                image.setAlbumId(String.valueOf(albums.get(i).getId()));
            }
            if (!TextUtils.isEmpty(albums.get(i).getOriUrl())) {
                image.isOri = true;
            }
            image.setWidth(albums.get(i).getWidth());
            image.setHeight(albums.get(i).getHeight());
            selectPathList.add(image);
            updateImage();
        }
        if (audios != null && audios.size() > 0) {
            try {
                recordeTime = Integer
                        .parseInt(audios.get(0).getUrl().substring(audios.get(0).getUrl().lastIndexOf("/") + 1));
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            voicePath = audios.get(0).getThumbnail();
            tv_voice_time.setText(recordeTime + "\"");
            isHasRecorde = true;
            setIsVoiceState(isHasRecorde);
        }
    }


}
